package com.example.order.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.example.order.R;
import com.example.order.pojo.Reservation;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WindowOrderDetailFragment extends Fragment {
    TextView titleTextView;
    ListView reservationListView;
    Button deleteButton,refreshButton;
    private String window_id;


    private static final String BASE_URL = "http://10.2.0.232:8080/backend-api-endpoint";


    public WindowOrderDetailFragment() {
        // 必需的空构造函数
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_window_order_detail, container, false);

        titleTextView = view.findViewById(R.id.titleTextView);
        reservationListView = view.findViewById(R.id.reservationListView);
//        deleteButton = view.findViewById(R.id.deleteButton);
        refreshButton = view.findViewById(R.id.refreshButton);

        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (window_id != null && !window_id.isEmpty()) {
                    getAllReservations();
                } else {
                    Log.e("ConsumerOrderDetail", "Consumer ID is null or empty");
                }
            }
        });


        Bundle args = getArguments();
        if (args != null) {
            window_id = args.getString("window_id", "");
        }

        // Log consumer_id to check if it's null
        Log.i("ConsumerOrderDetail", "Window ID: " + window_id);

        getAllReservations();
        return view;
    }

    public class GetAllReservationsTask extends AsyncTask<Void, Void, List<Reservation>> {

        private String window_id;


        public GetAllReservationsTask(String windowId) {
            this.window_id = windowId;
        }

        @Override
        protected List<Reservation> doInBackground(Void... voids) {

            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/getReservationByWindowId?window_id="+window_id;

            System.out.println(url);
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    // 解析获取到的订单列表
                    List<Reservation> reservationList = parseReservationList(responseBody);
                    return reservationList;
                } else {
                    Log.e("GetAllReservations", "Error: " + response.code());
                    return null;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("GetAllReservations", "Error: " + e.getMessage());
                return null;
            }
        }

        public class ReservationAdapter extends ArrayAdapter<Reservation> {
            public ReservationAdapter(Context context, List<Reservation> reservations) {
                super(context, R.layout.order_list_window_item_layout, reservations);
            }

            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.order_list_window_item_layout, parent, false);
                }

                Reservation reservation = getItem(position);

                TextView text1 = convertView.findViewById(R.id.text1);
                TextView text2 = convertView.findViewById(R.id.text2);
                TextView text3 = convertView.findViewById(R.id.text3);
                TextView text4 = convertView.findViewById(R.id.text4);
                TextView text5 = convertView.findViewById(R.id.text5);
                TextView text6 = convertView.findViewById(R.id.text6);
                TextView text7 = convertView.findViewById(R.id.text7);
                Button deleteButton = convertView.findViewById(R.id.deleteButton);
                Button pickupButton = convertView.findViewById(R.id.pickupButton);

                text1.setText("订单id: " + reservation.getBill_id());
                text2.setText("菜品名:" + reservation.getDish_name());
                text3.setText("数量:" + reservation.getQuantity());
                text4.setText("总价:" + reservation.getTotal());
                text5.setText("取餐时间:" + reservation.getPickupTime());
                text6.setText("取餐号:" + reservation.getReservation_result());
                text7.setText("状态:" + reservation.getStatus());

                // 设置按钮文本
                pickupButton.setText(reservation.getStatus());

                // 设置按钮是否可点击
                pickupButton.setEnabled(!reservation.getStatus().equals("已取餐"));

                // 为删除按钮设置点击监听器
                deleteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String selectedBillId = reservation.getBill_id();
                        if (selectedBillId != null && !selectedBillId.isEmpty()) {
                            deleteOrder(selectedBillId);
                        } else {
                            Log.e("ConsumerOrderDetail", "Selected Bill ID is null or empty");
                        }
                    }
                });

                // 为取餐按钮设置点击监听器
                pickupButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String selectedBillId = reservation.getBill_id();
                        if (selectedBillId != null && !selectedBillId.isEmpty()) {
                            pickupOrder(selectedBillId);
                        } else {
                            Log.e("ConsumerOrderDetail", "Selected Bill ID is null or empty");
                        }
                    }
                });

                return convertView;
            }
        }

        @Override
        protected void onPostExecute(List<Reservation> reservationList) {
            if (reservationList != null) {



                // 创建适配器

                ReservationAdapter adapter = new ReservationAdapter(getActivity(), reservationList);

                // 将适配器设置到ListView
                reservationListView.setAdapter(adapter);

                for (Reservation reservation : reservationList) {
                    // 根据需要在界面上显示订单信息
                    Log.d("reservation", "billID: " + reservation.getBill_id() + ", dishname: " + reservation.getDish_name());

                }
            }
        }
    }

    private List<Reservation> parseReservationList(String responseBody) {
        // 实现解析JSON的逻辑，将数据转换成 Reservation 对象列表
        // 这里需要根据您后端返回的数据格式进行解析
        List<Reservation> reservationList = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(responseBody);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonReservation = jsonArray.getJSONObject(i);
                Reservation reservation = new Reservation();
                reservation.setBill_id(jsonReservation.getString("bill_id"));
                reservation.setDish_name(jsonReservation.getString("dish_name"));
                reservation.setQuantity(jsonReservation.getString("quantity"));
                reservation.setTotal(jsonReservation.getString("total"));
                reservation.setPickupTime(jsonReservation.getString("pickup_time"));
                reservation.setReservation_result(jsonReservation.getInt("reservation_result"));
                reservation.setStatus(jsonReservation.getString("status"));

                // 其他字段的解析
                reservationList.add(reservation);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return reservationList;
    }

    public void getAllReservations() {
        new GetAllReservationsTask(window_id).execute();
    }


    // 新增取餐订单的 AsyncTask
    public class PickupOrderTask extends AsyncTask<Void, Void, Boolean> {

        private String billId;

        public PickupOrderTask(String billId) {
            this.billId = billId;
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/updateReservationStatus"; // 修改URL为更新订单状态的接口

            // 构建JSON请求体
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            String json = "{\"bill_id\":\"" + billId + "\", \"status\":\"已取餐\"}";
            RequestBody requestBody = RequestBody.create(JSON, json);

            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();


            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    // 取餐成功
                    return true;
                } else {
                    Log.e("PickupOrder", "Error: " + response.code());
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("PickupOrder", "Error: " + e.getMessage());
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                // 取餐成功，执行刷新订单列表的操作或其他操作
                Toast.makeText(getContext(), "取餐成功", Toast.LENGTH_SHORT).show();
                getAllReservations();
            } else {
                // 取餐失败，可以进行相应的处理
                Log.e("PickupOrder", "Failed to pickup order");
            }
        }
    }

    // 新增取餐的方法
    public void pickupOrder(String billId) {
        // 弹出确认对话框
        showConfirmationDialogForPickup(billId);
    }

    // 新增确认对话框的方法
    private void showConfirmationDialogForPickup(String selectedBillId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("确认取餐");
        builder.setMessage("确定要取餐吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击确定按钮，执行取餐操作
                pickupOrderConfirmed(selectedBillId);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击取消按钮，不执行任何操作
            }
        });
        builder.create().show();
    }

    // 新增取餐确认的方法
    private void pickupOrderConfirmed(String selectedBillId) {
        if (selectedBillId != null && !selectedBillId.isEmpty()) {
            // 直接调用取餐的 AsyncTask
            new PickupOrderTask(selectedBillId).execute();
        } else {
            Log.e("ConsumerOrderDetail", "Selected Bill ID is null or empty");
        }
    }


    // 新增删除订单的 AsyncTask
    public class DeleteOrderTask1 extends AsyncTask<Void, Void, Boolean> {

        private String billId; // 新增成员变量用于存储订单的 billId

        // 修改构造函数，接收consumer_id和billId参数并进行赋值
        private DeleteOrderTask1(String billId) {
            this.billId = billId;
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            String url = BASE_URL + "/deleteReservation/" + billId; // 修改URL，将billId添加到URL中

            Request request = new Request.Builder()
                    .url(url)
                    .delete()
                    .build();

            try {
                Response response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    // 订单删除成功
                    return true;
                } else {
                    Log.e("DeleteOrder", "Error: " + response.code());
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("DeleteOrder", "Error: " + e.getMessage());
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                // 订单删除成功，执行刷新订单列表的操作或其他操作
                Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                getAllReservations();
            } else {
                // 订单删除失败，可以进行相应的处理
                Log.e("DeleteOrder", "Failed to delete order");
            }
        }

    }


    private void showConfirmationDialog(String selectedBillId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("确认删除");
        builder.setMessage("确定要删除订单吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击确定按钮，执行删除订单操作
                deleteOrderConfirmed(selectedBillId);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击取消按钮，不执行任何操作
            }
        });
        builder.create().show();
    }


    // 新增删除订单的方法
    public void deleteOrder(String billId) {
        showConfirmationDialog(billId);
    }



    private void deleteOrderConfirmed(String selectedBillId) {
        if (selectedBillId != null && !selectedBillId.isEmpty()) {
            // 直接调用删除订单的方法
            new DeleteOrderTask1(selectedBillId).execute();
        } else {
            Log.e("ConsumerOrderDetail", "Selected Bill ID is null or empty");
        }
    }




}
